<template>
  <div class="note-add-page">
    <!-- 上部分 -->
    <div class="header">
      <el-button class="back-button" icon="el-icon-arrow-left" @click="goBack"></el-button>
      <div class="title">编辑笔记</div>
      <el-button class="finish-button" type="primary" @click="finishNote" :disabled="noteTitle.length == 0">完成</el-button>
    </div>
    <!-- 中间部分编辑区 -->
    <div class="editor-container">
      <el-input
          v-model="noteTitle"
          placeholder="请输入标题"
          class="title-input"
      ></el-input>

      <div class="content-editor">
        <QuillEditor class='quillEditorChild' ref='quillEditor' v-model="contentArea" @contentData="change($event)"></QuillEditor>
      </div>
    </div>

    <!-- 下部分区 -->
    <div class="bottom-toolbar">
      <el-button icon="el-icon-back" @click="undo" class="toolbar-button"></el-button>
      <el-button icon="el-icon-right" @click="redo" class="toolbar-button"></el-button>

      <el-button
          icon="el-icon-plus"
          @click="toggleAddMenu"
          class="toolbar-button add-button"
          ref="addButton"
      ></el-button>

    </div>

    <!-- 弹出层 -->
    <el-dialog
        :visible.sync="addMenuVisible"
        width="80vw"
        :show-close="false"
        custom-class="custom-add-menu"
        :modal="false"
    >
      <div class="add-menu-scroll-container">
        <div class="add-menu-content">
          <!--          图片-->
          <div class="add-menu-item">
            <div class="icon-container">
              <el-button @click="insertImage" class="icon-button">
                <i class="el-icon-picture"></i>
              </el-button>
            </div>
            <div class="text-container">插入图片</div>
          </div>
          <!--          声音-->
          <div class="add-menu-item">
            <div class="icon-container">
              <el-button @click="insertAudio" class="icon-button">
                <i class="el-icon-microphone"></i>
              </el-button>
            </div>
            <div class="text-container">插入声音</div>
          </div>
          <!--          文件-->
          <div class="add-menu-item">
            <div class="icon-container">
              <el-button @click="insertFile" class="icon-button">
                <i class="el-icon-tickets"></i>
              </el-button>
            </div>
            <div class="text-container">插入文件</div>
          </div>
        </div>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import QuillEditor from "@/components/QuillEditor";
import Quill from "quill";
import IndexedDBUtil from "@/utils/IndexDB";
export default {
  name: 'noteAdd',
  components: {
    QuillEditor
  },
  data() {
    return {
      noteId: null,
      noteTitle: '',
      contentArea: null,
      addMenuVisible: false,
      dbUtil: null,  // IndexedDB 工具类实例
      insertIndex: 0, // quill插入位置
    };
  },
  mounted() {
  },
  created() {
    this.dbUtil = new IndexedDBUtil('NotesDatabase', 'NotesStore');
    if (this.$route.query.id) {
      this.noteId = Number(this.$route.query.id)
    }
    console.log('noteId', this.noteId)
    this.loadEditNote()
  },
  methods: {
    goBack() {
      this.$router.push('/');
    },
    undo() {
      const quill = this.$refs.quillEditor.getQuillInstance();
      if (quill) {
        quill.history.undo();
      }
    },
    redo() {
      const quill = this.$refs.quillEditor.getQuillInstance();
      if (quill) {
        quill.history.redo();
      }
    },
    formattedDate() {
      const year = new Date().getFullYear();
      const month = String(new Date().getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，所以需要 +1
      const day = String(new Date().getDate()).padStart(2, '0'); // 日期是从 1 开始的

      return `${year}-${month}-${day}`; // 返回格式化后的日期
    },
    async finishNote() {
      const quill = this.$refs.quillEditor.getQuillInstance();
      // 获取 Delta 格式内容
      var delta = quill.getContents();
      // 获取 HTML 格式内容
      var html = quill.root.innerHTML;

      var note = {
        title: this.noteTitle,
        delta: JSON.stringify(delta),
        html: html,
        date: this.formattedDate()
      };
      if (this.noteId) {
        note = {
          id: this.noteId,
          title: this.noteTitle,
          delta: JSON.stringify(delta),
          html: html,
          date: this.formattedDate()
        };
        try {
          const result = await this.dbUtil.update(note);
          console.log('笔记已更新', result)
        } catch (error) {
          console.error('更新笔记失败:', error)
        }
      } else {
        try {
          // 保存 note 对象到 IndexedDB
          const result = await this.dbUtil.add(note);
          console.log('笔记已保存:', result);
        } catch (error) {
          console.error('保存笔记失败:', error);
        }
      }
      this.goBack()
    },
    toggleAddMenu() {
      const quill = this.$refs.quillEditor.getQuillInstance();
      var selection = quill.getSelection();
      if (selection) {
        this.insertIndex = selection.index
      }
      console.log('位置:', this.insertIndex, selection)
      this.addMenuVisible = !this.addMenuVisible;
    },
    insertImage() {
      const quill = this.$refs.quillEditor.getQuillInstance();
      const range = quill.getSelection();
      // let index = range ? range.index : quill.getLength();
      let index = range ? range.index : this.insertIndex ? this.insertIndex : quill.getLength()
      // 创建一个隐藏的文件选择对话框
      const input = document.createElement('input');
      input.type = 'file';
      input.accept = 'image/*'; // 只允许选择图片文件

      input.addEventListener('change', (event) => {
        const file = event.target.files[0];
        if (file) {
          const reader = new FileReader();
          reader.onload = (e) => {
            const imageURL = e.target.result;
            quill.insertEmbed(index, 'image', imageURL, Quill.sources.USER);
          };
          reader.readAsDataURL(file); // 读取文件内容作为 data URL
        }
      });

      input.click(); // 模拟点击文件选择对话框
      quill.insertText(quill.getLength(), '\n');
      quill.setSelection(quill.getLength());
      this.addMenuVisible = false;
    },
    insertAudio() {
      const quill = this.$refs.quillEditor.getQuillInstance();
      const input = document.createElement('input');
      input.type = 'file';
      input.accept = 'audio/*'; // 只允许选择音频文件

      input.addEventListener('change', (event) => {
        const file = event.target.files[0];
        if (file) {
          // 在实际应用中，您应该上传文件到服务器并获取文件的URL
          // 这里我们仅使用文件的本地路径作为示例（这在实际应用中并不可用）
          const audioLink = URL.createObjectURL(file);
          const range = quill.getSelection();
          let index = range ? range.index : quill.getLength();
          quill.insertText(index, audioLink, 'link', 'user');
        }
      });

      input.click();
      this.addMenuVisible = false;
    },
    insertFile() {
      this.addMenuVisible = false;
    },
    change(event) {
      console.log('更新值:', event)
    },
    loadContent(content, fileName) {
      this.noteTitle = fileName.replace('.json','')
      const quill = this.$refs.quillEditor.getQuillInstance();
      if (fileName.endsWith('.html') || fileName.endsWith('.htm')) {
        quill.root.innerHTML = content;
      } else if (fileName.endsWith('.json')) {
        const delta = JSON.parse(content);
        quill.setContents(delta);
      }
    },
    loadEditNote() {
      if (!this.noteId) {
        return
      }
      this.dbUtil.getById(this.noteId).then(res => {
        console.log('值', res)
        this.loadContent(res.delta, res.title + ".json")
      })
    },
  },
};
</script>

<style scoped>
.note-add-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #fff;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #f5f5f5;
  height: 10%;
}

.title {
  flex: 1;
  text-align: center;
  font-size: 18px;
  font-weight: bold;
}

.finish-button {
  margin-left: 10px;
}

.editor-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  height: 80%;
}

.title-input {
  margin-bottom: 10px;
}

.content-editor {
  flex: 1;
}

.quillEditorChild {
  width: 100%;
}

.bottom-toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px;
  background-color: #f5f5f5;
  box-shadow: 0 -1px 5px rgba(0, 0, 0, 0.1);
  height: 10%;
}

.add-menu-scroll-container {
  display: flex;
  overflow-x: auto;
  white-space: nowrap;
  padding: 10px;
}

.add-menu-content {
  display: flex;
  align-items: center;
}

.add-menu-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 0 10px;
}

.icon-container {
  margin-bottom: 4px;
}

.text-container {
  text-align: center;
}

.custom-add-menu .el-dialog__header {
  display: none;
}

.custom-add-menu .el-dialog__body {
  padding: 0;
}

.custom-add-menu .el-dialog {
  position: absolute;
  top: 0;
  left: 50%;
  transform: translateX(-50%);
  margin-top: -10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
}

</style>